import { useEffect, useRef, useState } from "react";
import { invoke } from "@tauri-apps/api/tauri";
import useEscape from "./hooks/useEscape";
import "./App.css";
import { MD5 } from "./api/md5";
import { fetch, ResponseType } from "@tauri-apps/api/http";

const appid = "你的百度翻译appid";
const key = "你的百度翻译appkey";

const http = (data: Record<string, string>) => {
  return new Promise((resolve, reject) => {
    fetch("http://api.fanyi.baidu.com/api/trans/vip/translate", {
      method: "GET",
      headers: {
        "content-type": "application/json",
      },
      responseType: ResponseType.JSON,
      timeout: 60000,
      query: data,
    })
      .then((res) => {
        resolve(res);
      })
      .catch((e) => {
        reject(e);
      });
  });
};

function App() {
  useEscape();
  useEffect(() => {
    invoke("init_spotlight_window");
  }, []);

  const inputRef = useRef<HTMLTextAreaElement>(null);
  const [text, setText] = useState<string>("默认");

  let metaHold = false;

  const tran = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.code !== "AltRight") {
      return;
    }
    const question = inputRef.current?.value || "";
    if (!question) {
      setText("请输入内容");
      return;
    }
    setText("等待中");

    const salt = new Date().getTime();
    const from = metaHold ? "en" : "zh";
    const to = metaHold ? "zh" : "en";
    const str1 = appid + question + salt + key;
    const sign = MD5(str1);

    http({
      q: question,
      appid: appid,
      salt: `${salt}`,
      from: from,
      to: to,
      sign: sign,
    }).then((data: any) => {
      setText(data.data.trans_result[0].dst);
    });
  };

  const copy = () => {
    navigator.clipboard.writeText(text);
  };

  return (
    <div
      className="container"
      onKeyDown={(e) => {
        if (e.key === "Meta") {
          metaHold = true;
        }
      }}
      onKeyUp={(e) => {
        if (e.key === "Meta") {
          metaHold = false;
        }
      }}
    >
      <textarea ref={inputRef} onKeyUp={tran}></textarea>
      <div onClick={copy}>{text}</div>
    </div>
  );
}

export default App;
